//
//  LoginApi.m
//  SmartWindow
//
//  Created by 喻贵华 on 15/12/16.
//  Copyright © 2015年 Demo. All rights reserved.
//

#import "LoginApi.h"
#import "GetUserInfoApi.h"    // 获得用户信息api
#import "NSString+Password.h"
#import "AppDelegate.h"

@implementation LoginApi{
    NSDictionary *_dic;
}

-(id)initWithDic:(NSDictionary *)dic{
    if (self = [super init]) {
        _dic = dic;
    }
    return self;
}

- (NSString *)requestUrl {
    return @"/new/user/login";
}

- (YTKRequestMethod)requestMethod {
    return YTKRequestMethodPOST;
}

- (id)requestArgument {
    NSMutableDictionary *dic = [NSMutableDictionary getPubdicGuest];
    if (_dic[@"username"]) {
        
        NSString* base64Text = [NSString encryptUseAES:_dic[@"username"] key:nil];
        
        [dic setObject:base64Text forKey:@"username"];
        
    }
    if (_dic[@"password"]) {
         NSString* base64Text = [NSString encryptUseAES:_dic[@"password"] key:nil];
        
        [dic setObject:base64Text forKey:@"password"];
        
    }
    NSString *sign=[NSString getSign:dic];
    [dic setObject:sign forKey:@"sign"];
    return dic;
}

- (NSString *)userId {
    return [[[self responseJSONObject] objectForKey:@"userId"] stringValue];
}

-(void)analyseResponseObject {
    
    NSDictionary * dict = [self responseJSONObject];
    NSLog(@"dict = %@",dict[@"errmsg"]);
    if ([dict[@"errcode"] intValue] == 0) {
        
        [SVProgressHUD showSuccessWithStatus:@"您已安全登录！"];
        SAVE_OBJECT(_dic[@"username"], USERNAME);
        SAVE_OBJECT(_dic[@"password"], PASSWORD);
        SAVE_OBJECT(dict[@"data"][@"uid"], DTUID);
        SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
        SAVE_OBJECT(@"YES", @"Login");   // 登录状态保存来设置根控制器
        NSLog(@"%@",EXRACT_OBJECT(DTUID));
        
        
    } else {
         [SVProgressHUD showErrorWithStatus:dict[@"errmsg"]];
    }
}



- (void)GetUserInfo {
    
    GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
    [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [userInfoApi analyseResponseObject];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"获取用户信息失败！"];
    }];
    
}


-(void)dealloc
{
    NSLog(@"RegisterApi dealloc");
}
  
@end
